package com.xcc.config;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.Map;

/**
 * @Description: MyAckReceiver
 * @Author xiechuang
 * @Date 2022/12/8
 */
@Component
public class MyAckReceiver implements ChannelAwareMessageListener {

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            byte[] body = message.getBody();
            ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(body));
            Map<String, String> map = (Map<String, String>) ois.readObject();
            String messageId = map.get("messageId");
            String messageData = map.get("messageData");
            String createTime = map.get("createTime");
            ois.close();

            if ("directQueue".equals(message.getMessageProperties().getConsumerQueue())) {
                System.out.println("MyReceiver messageId：" + messageId + ", messageData：" + messageData + ", createTime：" + createTime);
                System.out.println("消费的主题消息来自：" + message.getMessageProperties().getConsumerQueue());
                // 处理相应业务流程
            }

            if ("fanout.key1".equals(message.getMessageProperties().getConsumerQueue())) {
                System.out.println("MyReceiver messageId：" + messageId + ", messageData：" + messageData + ", createTime：" + createTime);
                System.out.println("消费的主题消息来自：" + message.getMessageProperties().getConsumerQueue());
                // 处理相应业务流程
            }

            channel.basicAck(deliveryTag, true);
        } catch (Exception e) {
            channel.basicReject(deliveryTag, false);
            e.printStackTrace();
        }

    }

}
